package org.mathcloud.math.core.scilab.operator.algebra;

import org.apache.log4j.Logger;
import org.mathcloud.math.core.common.operator.algebra.Divide;
import org.mathcloud.math.core.scilab.factory.ScilabQuantityObjectFactory;
import org.mathcloud.math.core.scilab.manager.ScilabSupervisor;
import org.mathcloud.math.core.scilab.operator.ScilabBinaryOperator;
import org.mathcloud.math.core.scilab.quantity.ScilabQuantityObject;
import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.types.ScilabDouble;


public class ScilabDivide extends ScilabBinaryOperator implements Divide
{
	public ScilabDivide()
	{
		super();
		signature.setMMLContentTag("divide");
	}
	@Override
	public void calculate()
	{
		if (getResultSignature()!=null)
	  {
	    String sciJob;
	    String tmpVar = "tmp_"+ScilabSupervisor.getVarId();
			ScilabQuantityObject tOp1 = ScilabQuantityObjectFactory.getInstance(operand1);
			ScilabQuantityObject tOp2 = ScilabQuantityObjectFactory.getInstance(operand2);
			sciJob = tmpVar;
			sciJob = sciJob + "="+ tOp1.getVarName();
	    sciJob = sciJob + "/";
	    sciJob = sciJob + tOp2.getVarName();;
	    sciJob +=";";  
	    if (sciEngine.exec(sciJob))
	    {
	    	log.info(sciJob);
	    	try
				{
	    		ScilabDouble tRes = (ScilabDouble)sciEngine.get(tmpVar);
	      	res = ScilabQuantityObjectFactory.getInstance(tRes);
					sciJob = "clear "+tmpVar+";";
					if (sciEngine.exec(sciJob))
						log.info(sciJob);					      	
				} catch (JavasciException e)
				{
					log.error(e);
				}
	    }
	    else
	    {
	    	res = null;
	    	log.info(sciJob + " - " + sciEngine.getLastErrorMessage());
	    }
	  }    						
	}	
	
	private static final Logger log = Logger.getLogger(ScilabDivide.class);
}
